package com.ideaaedi.demo.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ideaaedi.commonds.time.DateTimeConverter;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * (non-javadoc)
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
@RestController
public class TestController {
    
    private final static List<JSONObject> ELASTALERT_ALARM_LIST = new CopyOnWriteArrayList<>();
    
    @Resource
    private HttpServletRequest httpServletRequest;
    
    @RequestMapping("/test")
    public String test() {
        return DateTimeConverter.REGULAR_DATE_TIME.now() + "\n" + RandomStringUtils.random(10, true, true);
    }
    
    
    @PostMapping("/elastalert-alarm/receive")
    public String receiveElastalertAlarm(@RequestBody String alermInfo) {
        JSONObject element = JSON.parseObject(alermInfo);
        JSONObject requestHeader = new JSONObject();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            requestHeader.put(headerName, httpServletRequest.getHeader(headerName));
        }
        element.put("requestHeader", requestHeader);
        ELASTALERT_ALARM_LIST.add(0, element);
        while (ELASTALERT_ALARM_LIST.size() > 100) {
            ELASTALERT_ALARM_LIST.remove(ELASTALERT_ALARM_LIST.size() - 1);
        }
        return "ok";
    }
    
    
    @RequestMapping("/elastalert-alarm/list")
    public List<JSONObject> list100ElastalertAlarm() {
        return ELASTALERT_ALARM_LIST;
    }
    
}
